package com.yrd.centerlogclient;

import java.util.Date;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LocationInfo;
import org.apache.log4j.spi.LoggingEvent;

import com.alibaba.fastjson.JSON;
import com.rzrk.centerlog.entity.NormalLog;

public class CenterLogAppender extends AppenderSkeleton {
	private String url;
	private String hwm; //set hwm时生成sender 注意顺序
	private String module;
	
	private Sender sender;
	
	public Sender getSender() {
		return sender;
	}

	public void close() {
		sender.stop();
	}

	public boolean requiresLayout() {
		return false;
	}
	@Override
	protected void append(LoggingEvent event) {
		String message = (layout==null)? event.getMessage().toString() : layout.format(event);
		String level = event.getLevel().toString();
		String loggerName = event.getLoggerName();
		String threadName = event.getThreadName();
		LocationInfo locationInfo = event.getLocationInformation();
		NormalLog normalLog = new NormalLog();
		normalLog.setContentText(message);
		normalLog.setIp(Utils.getRealIp());
		normalLog.setModule(module);
		normalLog.setCreateDate(new Date());
		normalLog.setLevel(level);
		normalLog.setLoggerName(loggerName);
		normalLog.setThreadName(threadName);
		normalLog.setClassName(locationInfo.getClassName());
		normalLog.setMethodName(locationInfo.getMethodName());
		normalLog.setFileName(locationInfo.getFileName());
		normalLog.setLineNumber(locationInfo.getLineNumber());
		
		sender.postNormal(JSON.toJSONString(normalLog));
	}

	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getHwm() {
		return hwm;
	}
	public void setHwm(String hwm) {
		this.hwm = hwm;
		this.sender = Sender.createInstance(url,Long.parseLong(hwm));
	}

	public String getModule() {
		return module;
	}
	public void setModule(String module) {
		this.module = module;
	}

	public PatternLayout getLayout() {
		return (PatternLayout) layout;
	}
	public void setLayout(PatternLayout layout) {
		this.layout = layout;
	}

	

}
